(function($) {
/******************************
*
* COMMON
*
*******************************/
	KOR.namespace('KOR.behaviors').setAjaxLoader()

	KOR.toggler('.kor-toggle');

	/**
	 * Register the validator on a forms
	 **/
	KOR.behaviors.setValidators();

	/**
	 * Register the accordion on all matched selectors
	 **/
	KOR.behaviors.setAccordions();

	/**
	 * Initialize various Tabsets
	 **/
	KOR.behaviors.setTabsets();

	/**
	 * Sets the action of a form to the value of the forms data-ajax-url attribute if it exists
	 **/
	KOR.behaviors.setAjaxFormsAction();
	
	/**
	 * Initialize various product sliders
	 */
	KOR.behaviors.setCarousels();

	/**
	 * Initialize ZoomRotate
	 **/
	KOR.behaviors.setZoomRotate();

	/**
	 * Initialize flyout zoom
	 */
	KOR.behaviors.setFlyoutZoom();

	KOR.behaviors.setTips();
	KOR.behaviors.setTipMenus();
	KOR.behaviors.setOverlays();

	$(document).delegate('[data-kor-submit-form]', 'click', function(ev){
		$($(ev.currentTarget).attr('data-kor-submit-form')).submit()
	})

	/**
	 * Generic listener: On change of selectbox submit form
	 **/
	$(document).delegate('[data-submit-form-handler=change]', 'change', function(ev){
		$(ev.currentTarget).closest('form').submit()
	})

	/**
	 * Opens a popup window
	 **/

	$(document).delegate('.kor-open-as-popup', 'click', function(ev){
		var target=$(ev.currentTarget)
		window.open(ev.currentTarget.href,target.attr('data-popup-title'),target.attr('data-popup-properties'));
		return false;
	})


	/**
	 * Hijacks links inside a dialog inorder to open the content within the dialog itself
	 **/
	$(document).delegate('.kor-overlay a[data-hijax=true]', 'click', KOR.behaviors.dialogHijaxHandler);

	/**
	 * Hijacks the submission of forms
	 **/
	$(document).delegate('.kor-overlay [data-hijax=true] form:not([data-hijax=false])', 'submit', KOR.behaviors.formHijaxHandler);

	/**
	 * Updates a hidden input field with the name of the button that submitted the form via ajax
	 * This is required so the backend knows what action is being requested from the form
	 **/
	$(document).delegate('.kor-overlay [data-hijax=true] form [type=submit], .kor-overlay [data-hijax=true] form [name=cancel], .kor-overlay [data-hijax=true] form [type=cancel]', 'click', function(ev){
		$('[data-form-action=true]',$(ev.currentTarget).closest('form')).attr('name', ev.currentTarget.name)
	});

	/**
	 * Generic listener for opening a new browser window
	 **/
	$(document).delegate('.ws-open-new-window', 'click', function(ev){
		var el = $(ev.currentTarget)
		window.open(el.attr('data-open-window'))
	})

	/**
	 * Generic listener for hover states
	 **/
	$(document).delegate('[data-hover]', 'hover', function(ev){
		var el = $(ev.currentTarget);
		var c = el.attr('data-hover-class') || 'kor-hover';
		el.toggleClass(c);
	})

/***************************
*
* 		HEADER
*
****************************/
	KOR.behaviors.setMiniCart();
	KOR.behaviors.setDropNavs();

/******************************
*
* SEARCH
*
*******************************/

	/**
	 * Will listen for click on any element with class change-document-location and go to that page
	 **/
	$(document).delegate('.ws-change-document-location', 'click', function(ev){
		document.location.href = $(ev.currentTarget).attr('data-document-location')
	})

	/**
	 * Enables collapsing of filter groups in parametric nav
	 **/
	$(document).delegate('.ws-filters .ws-header', 'click', function(e){
		var el = $(e.currentTarget)
		if (el.hasClass('ws-collapsed')){
			el.removeClass('ws-collapsed').next('ul').slideDown()
		}else{
			el.addClass('ws-collapsed').next('ul').slideUp()
		}
	})

	KOR.behaviors.setSuggest();
	KOR.behaviors.setSearchBehaviors()

/*************************
*
* 		CHECKOUT
*
**************************/

	KOR.behaviors.setPromoBehaviors()

	/**
	 * Fix for IE
	 * IE doesn't submit the values of buttons in forms, so I'm updating a hidden input field with the values of the clicked button
	 **/
	$(document).delegate('form.ws-cartForm button[type=submit]','click',function(ev){
		var target = $(ev.target)
		$('[data-form-action=true]',target.closest('form')).attr('name', ev.currentTarget.name).attr('value', target.attr('data-value'))
		target.attr('name',"blah")
	})

	/**
	 * slider for using different address
	 **/
	$(document).delegate('input[name=ShippingAddressOption]', 'change', function(){
		if($(this).hasClass('ws-shipOption2')){
			$('.ws-shipopt2').slideDown()
		}else{
			if($('.ws-shipopt2').css('display')!='none'){
				$('.ws-shipopt2').slideUp()
			}
		}
	})

	$(document).delegate('.ws-shipping-instruction textarea', 'mouseover', function(ev){
		var target = $(this);
		if(!target.data('shipping-events')){
			target.bind('cut paste', function(ev){
				var textarea = $(this);
				setTimeout(function(){ textarea.blur().focus(); }, 100)
			})
			target.data('shipping-events', 'true')
		}
	})

	$(document).delegate('.ws-shipping-instruction textarea', 'keydown keyup', function(ev){
		var max = $(this).attr('maxlength')
		var k = ev.keyCode
		if(this.value.length > max){
			ignore = (k == 8 || (k > 36 && k < 41) || k == 46 || k == 17 || k == 99 || (ev.ctrlKey && k == 67) || (ev.metaKey && k == 67));
			if (!ignore){
				this.value = this.value.substring(0, max)
			}
		}
		$('.ws-shipping-instruction .kor-shipping-instructions-length').html(' ' + max - this.value.length + ' ')
	})

	KOR.behaviors.setAddressBookBehaviors()

	/**
	 * enter promotion code and submit shoppingCartCommand or checkoutForm with "onenter" from input field
	 **/
	$(document).delegate('input.ws-usePromotionCode, input.ws-promotion-code-input', 'keydown', function(ev) {
		if (ev.keyCode == 13) {
			var target = $(ev.currentTarget)
			target.parent().append('<input type="hidden" name="'+ target.next('button').attr('name') +'"/>')
			$(ev.currentTarget).closest('form').submit();
			return false;
		}
	});

	/***
	 * user can enter credit card data and press enter key and the credit card form will be submitted
	 */
	$(document).delegate('.ws-payment-methods input:not([class=ws-usePromotionCode])', 'keydown', function(ev) {
		if (ev.keyCode == 13) {
			$(ev.target).closest('form').submit()
			return false;
		}else{
			return true;
		}
	});

	/***
	 * user can enter gift card and press enter key and the gift card form will be submitted
	 */
	$(document).delegate('.ws-gift-cards input', 'keydown', function(ev) {
		if (ev.keyCode == 13) {
			$('.ws-applyGiftCard').click();
			return false;
		}else{
			return true;
		}
	});

	/* edit - slider for address book */
	$(document).delegate('.address .ws-edit button.ws-edit', 'click', function(ev) {
		var target = $(ev.currentTarget)

		var currentEditArea = $('div.ws-edit-form', target.closest('tr.address').next());

		/* slide all open edit areas up but let the current untouched*/
		$('div.ws-edit-form').filter(function(index) {
			  if (currentEditArea == this) {return false;}
			  return true;
		}).slideUp();

		/* show the wished edit area */
		$(currentEditArea).slideDown();
	});

	/**
	 * Show the add new address form
	 * Hide the add new address link
	**/
	$(document).delegate('.kor-add-new-shipping-address-link', 'click', function() {
		$('.ws-checkout .kor-add-new-shipping-address').slideDown();
		return false;
	});

	/**
	 * Change the billing/shipping address
	**/
	$(document).delegate('select.ws-useAsBilling, select.ws-useAsShipping', 'change', function(ev) {
		var target = $(ev.currentTarget)
		var form = target.closest('form')
		if ( target.attr('data-form-action-key') != null && target.attr('data-form-action-key') == 'changeAddress' ){
			form.attr('action',form.attr('action')+'?'+$(this).attr('data-form-action-key')).submit();
		}
	});

	/* show delete address confirmation*/
	$(document).delegate('.ws-address-book .ws-remove-shipping-address-link', 'click', function() {
		$(this).parent().hide();
		$('.ws-checkout .address-book .ws-manageshippingaddress ').hide();
		$(this).parent().next().show();
	});

	/* delete address cancellation*/
	$(document).delegate('.address .ws-edit a.ws-deletecancellation', 'click', function() {
		$(this).parent().hide();
		$(this).parent().prev().show();
		$('.ws-checkout .address-book .ws-manageshippingaddress ').show();

	});

	/* cancel - slider for address book */
	$(document).delegate('.ws-edit-form button.ws-cancel', 'click', function() {
		$('div.ws-edit-form').slideUp();
	});

	/* ship to multiple address submit */
	$(document).delegate('.ws-applymultipleshiptoaddresses', 'click', function() {
		$('.ws-checkout .ws-itemDestinationForm').submit();
		return true;
	});

	//$(document).delegate('.ws-continue-checkout .ws-button', 'click', function(ev){
	$(document).delegate('.ws-continueForm', 'submit', function(ev){
		var defaultShip = $('input.ws-useAsShipping[data-defaultshiptoaddress]').get(0)
		if(defaultShip && $('.ws-useAsShipping[checked=checked').get(0) != defaultShip){
			$('.ws-use-as-default-ship').click()
			return false;
		}
	})

	$(document).delegate('.ws-defaultShipToNo', 'click', function(ev){
		$(document).undelegate('.ws-continueForm', 'submit')
		$('.continueForm').submit()
	})

	$(document).delegate('.ws-defaultShipToYes', 'click', function(ev){
		var form = $('.ws-continueForm')
		$(document).undelegate('.ws-continueForm', 'submit')
		form.append('<input type=hidden name=setDefaultShipTo value="true"/>')
		form.submit()
	})


	/**
	 * Gifting option site
	 **/
	$(document).delegate('form[name=GiftingForm] .kor-giftRadioYes', 'click', function(ev){
		$(this).closest('td').find('.kor-giftOptions').slideDown();
	})
	
	$(document).delegate('form[name=GiftingForm] .kor-giftRadioNo', 'click', function(ev){
		$(this).closest('td').find('.kor-giftOptions').slideUp();
		$(this).closest('td').find('.kor-giftOptions input, .kor-giftOptions textarea').val("");
	})
	
	$(document).delegate('form[name=GiftingForm] .kor-packSlipRadioYes', 'click', function(ev){
		$( ev.target ).closest('.kor-packSlipArea').find('.kor-giftOptions').slideDown();
	})
	
	$(document).delegate('form[name=GiftingForm] .kor-packSlipRadioNo', 'click', function(ev){
		$( ev.target ).closest('.kor-packSlipArea').find('.kor-giftOptions').slideUp();
		$( ev.target ).closest('.kor-packSlipArea').find('.kor-giftOptions input, .kor-giftOptions textarea').val("");
	})
	
	$(document).delegate('form[name=GiftingForm] .kor-packSlipLink', 'click', function(ev){
		if($( ev.target ).closest('td').find('.kor-packSlipArea').is(':visible'))
		{
			$( ev.target ).closest('td').find('.kor-packSlipArea').slideUp();
		}
		else
		{
			$( ev.target ).closest('td').find('.kor-packSlipArea').slideDown();
		} 
		return false;
	})
	

	$(document).delegate('form[name=GiftingForm] button[name=continue]', 'click', function(ev){

		var currentSite = Number($('form[name=GiftingForm] div.kor-giftWizardPage:visible').attr('data-site'));

		if($('form[name=GiftingForm] .kor-giftWizard'+(currentSite+1)).length>0)
		{
			$('form[name=GiftingForm] .kor-giftWizard'+currentSite).slideUp();
			currentSite++;
			$('form[name=GiftingForm] .kor-giftWizard'+currentSite).slideDown();
			$('form[name=GiftingForm] button[name=backSite]').show();
			return false;
		}
		else
		{
			return true;
		}
	})
	
	$(document).delegate('form[name=GiftingForm] button[name=backSite]', 'click', function(ev){

		var currentSite = Number($('form[name=GiftingForm] div.kor-giftWizardPage:visible').attr('data-site'));

		if(currentSite>0)
		{
			$('form[name=GiftingForm] .kor-giftWizard'+currentSite).slideUp();
			currentSite--;
			$('form[name=GiftingForm] .kor-giftWizard'+currentSite).slideDown();
			
			if(currentSite==0)
			{
				$(this).hide();
			}
		}
		
		return false;
	})
	
	$(document).delegate('form[name=GiftingForm] textarea', 'keyup', function(ev){
		$('#'+$(ev.target).attr('data-charactercounter')).html($(ev.target).attr('data-maxcharacter')-$(ev.target).val().length);
	})
	
	$(document).ready(function() {
		$('form[name=GiftingForm] textarea').each(function(ev) {
		    $('#'+$(this).attr('data-charactercounter')).html($(this).attr('data-maxcharacter')-$(this).val().length);
		 });
		 
		 var currentSite = Number($('form[name=GiftingForm] div.kor-giftWizardPage:visible').attr('data-site'));

		 if(currentSite>0)
		 {
		 	$('form[name=GiftingForm] button[name=backSite]').show();
		 }
	});
	
	
	

	/**
	 * payment -> automatic select cc if you edit one cc field
	 */
	$(document).delegate('li.ws-method input[type="text"], li.ws-method select:not([data-editfields="true"])', 'click', function() {
		var paymentWallet = $(this).closest('li.ws-payment-wallet-list-item')
		if(paymentWallet.length>0){
			if(!$('label input[name="PaymentServiceSelection"]',paymentWallet).is(":checked")){
				$('label input[name="PaymentServiceSelection"]',paymentWallet).click();
			}
		}else if(!$('label input[name="PaymentServiceSelection"]',$(this).closest('li.ws-method')).is(":checked")){
			$('label input[name="PaymentServiceSelection"]',$(this).closest('li.ws-method')).click();
		}
	});

	/**
	 * CheckoutReview.isml -> sets the shippingMethod on the OrderReview page
	 **/
	$(document).delegate('select.ws-shipingMethod', 'change', function(ev) {
		var target = $(ev.currentTarget)
		var form = target.closest('form')
		if ( target.attr('data-form-action-key') != null && target.attr('data-form-action-key') == 'changeShippingMethod' ){
			$('[type=submit]', form).attr('disabled', 'disabled')
			$('#terms-conditions-agree').removeAttr('data-validate')
			form.attr('action',form.attr('action')+'?'+$(this).attr('data-form-action-key')).submit();
		}
	});

	/**
	 * checkout cart summary -> more items / hide items behavior
	 **/
	$(document).delegate('a.ws-show-all', 'click', function(ev){
		if($(this).html().match($(this).attr('data-showtext'))){
			$('table.ws-cartSummaryRemainList').slideDown()
			$(this).html($(this).attr('data-hidetext'))
		}else if($(this).html().match($(this).attr('data-hidetext'))){
			$('table.ws-cartSummaryRemainList').slideUp()
			$(this).html($(this).attr('data-showtext'))
		}
		return false;
	})

	KOR.behaviors.setCountryDropdown();

	/**
	 * Shipping selection auto form submit
	 **/
	$(document).delegate('.ws-shipping-methods input[type=radio]', 'change', function(ev){
		$('.ws-shipping-methods input[type=radio]').attr('disabled', true)
		var form = $(ev.target).closest('form').first()
		form.append('<input type="hidden" name="'+ ev.currentTarget.name +'" value="'+ $(ev.currentTarget).val() +'"/>');
		form.attr('action', form.attr('action') + "?" + ev.currentTarget.name + "=" + $(ev.currentTarget).val())
		form.submit();
	})

	/**
	 * Payment site
	 **/

	/**
	 * open the correct editBox in error case
	 */
	$(document).ready(function() {
		$('.errorCCEditLink').click();
	});

	KOR.behaviors.setCCWalletBehaviors();
	KOR.behaviors.setCCfieldBehaviors();

	$(document).delegate('.ws-updateable', 'mouseover focus', function(ev){
		var el = $(ev.currentTarget)
			if(!el.attr('data-originalvalue')){
				if (ev.currentTarget.type == 'checkbox' || ev.currentTarget.type == 'radiobutton'){
					el.attr('data-originalvalue', el.attr('checked'))
				}else{
					el.attr('data-originalvalue', el.val())
				}
			}
		}
	)

	/**
	 * Fires a product change event when any "updateable" attribute is changed on the cart page
	 **/
	$(document).delegate('.ws-updateable', 'change', function(ev){
		var el = $(ev.currentTarget)
		var newval = null
		if(el.attr('data-originalvalue')){
			if (ev.currentTarget.type == 'checkbox' || ev.currentTarget.type == 'radiobutton'){
				newval = el.attr('checked').toString()
			}else{
				newval= el.val()
			}
			if (newval != el.attr('data-originalvalue')) {
				el.attr('data-changed', true)
				el.addClass('kor-highlight')
			}else{
				el.removeAttr('data-changed')
				el.removeClass('kor-highlight')
			}
			//el.closest('.hproduct').trigger('cart:product-changed')
		}
	})

	/**
	 * Observes product change event and adjust the view of the "Edit" button accordingly
	 **/
	$(document).delegate('.hproduct', 'cart:product-changed', function(ev){
		var target = $(ev.currentTarget)
		if($('[data-changed=true]', target).length >0){
			$('button.ws-update-cart', target).addClass('ws-user-active')
		}else{
			$('button.ws-update-cart', target).removeClass('ws-user-active')
		}
	})

	/**
	 * Collaps / Expand Product Customization details on cart
	 **/
	$(document).delegate('.kor-customization-details .ws-close', 'click', function(e){
		$('.kor-customization-details').hide();
		$('.kor-customization-collapsed').show();
		return false;
	})
	
	$(document).delegate('.kor-customization-collapsed a', 'click', function(e){
		$('.kor-customization-collapsed').hide();
		$('.kor-customization-details').show();
		return false;
	})
	
	/**
	 * Print Receipt
	 **/
	$(document).delegate('.ws-print-receipt, .ws-print-link', 'click', function(e){
		window.print();
		return false;
	})

	/**
	 * Show inline product edit in cart
	 * Using "bind" otherwise the form will submit
	 **/
	$(document).delegate('.hproduct .ws-product-specs button.ws-edit', 'click', function(ev){
		var el = $(ev.currentTarget)
		el.closest('.ws-edit-product-variation').hide()
		$('.ws-product-variation', el.closest('.ws-product-specs')).show()
		return false;
	})

	/**
	 * Hide inline product edit in cart
	 * Using "bind" otherwise the form will submit
	 **/
	$(document).delegate('.hproduct .ws-product-specs button.ws-cancel', 'click', function(ev){
		var el = $(ev.currentTarget)
		el.parents('.ws-product-variation').hide()
		$('.ws-edit-product-variation', el.parents('.ws-product-specs')).show()
		return false;
	})

	/**
	 *
	 **/
	$(document).delegate('.ws-shipAddress .ws-shipOpt', 'click', function(ev){
		var el = $(ev.currentTarget)
		var form = el.closest('form')
		form.attr('action', el.attr('data-form-action'))
		form.submit()

	})

/**************************************
*
* ACCOUNT Section
*
**************************************/
KOR.behaviors.setAccountSection()

/**************************************
*
* FOOTER
*
******************************************/

/* country toggle*/
$(document).delegate('.ws-change-country .ws-country-list','focus', function(e){
	var obj = $(e.target)
	if(!obj.data('changeRegistered')){
		obj.data('changeRegistered',true)
		obj.change(function(e){
			e.target.form.submit();
		})
	}
})

/**************************************
*
* PRODUCT VIEW
*
******************************************/
	KOR.behaviors.setProductView();
/**
*Power reviews
*/
	$(document).delegate('.ws-reviews-tab-link','click',function(ev){
		$('.ws-collection-link-list-navigation [href="'+$(this).attr('href')+'"]').click();
	});
	
})(jQuery);

/**************************************
*
* My Account
*
******************************************/
	KOR.behaviors.setOrderHistory();